import { useCallback, useEffect, useState } from 'react';
import Styles from './index.module.less'
import { Fieldset, TextInput, Button, Group } from '@mantine/core';
import { Alert } from '@mantine/core';
import toast from 'react-hot-toast';
import { ClientAxios } from '@/common/useAxios';
function Login({type}){
    const [nickShow,setNickShow] = useState(false)
    const [zhanghao,set_zhanghao] = useState('')
    const [mima,set_mima] = useState('')
    const [nick,set_nick] = useState('')
    const submit = ()=>{
        if(!zhanghao){
            toast('请输入账号')
            return;
        };
        if(!mima){
            toast('请输入密码')
            return;
        };
        // Alert.
        if(nickShow){
            if(!nick){
                toast('请输入昵称')
                return;
            };
        }
        ClientAxios.post('/user/login',{
            account:zhanghao,
            password:mima,
            nickname:nick||undefined
        }).then(({data:res})=>{
            if(res.code==1){
                toast(res.msg)
                setTimeout(() => {
                    if(type == 2){
                        location = '/'
                    }else{
                        location = location
                    }
                    
                }, 1000);
            }else if(res.code == -2){
                setNickShow(true)
                toast(res.msg)
            }else{
                toast(res.msg)
            }
        })
    }
    const keyup = (e)=>{
        if(e.keyCode === 13){
            submit();
        }
    }
    useEffect(()=>{
        window.toast = toast
    },[])
    return (
        <div className={Styles.cont}>
            <Fieldset legend="登录/自定义注册">
                <TextInput maxLength={12} onChange={(e)=>{set_zhanghao(e.target.value)}} value={zhanghao} label="账号" placeholder="请输入账号" />
                <TextInput maxLength={10} onKeyUp={keyup} onChange={(e)=>{set_mima(e.target.value)}} value={mima} label="密码" placeholder="请输入密码" mt="md" />
                {
                    nickShow && <TextInput maxLength={12} onChange={(e)=>{set_nick(e.target.value)}} value={nick} label="昵称" placeholder="请输入昵称" mt="md" />
                }
                
                <Group justify="flex-end" mt="md">
                    <Button onClick={submit}>登录/注册</Button>
                </Group>
            </Fieldset>
        </div>
    )
}
export default Login